import fullscreen from 'vue-fullscreen'
import Vue from 'vue'
import { heightAndCenter, initTDTLayer, mapAndCenter } from '@/utils/map/mapTools3x'
import MapConfig from '@/utils/map/MapConfig'
import loadScript from '@/store/modules/mapModular'
import { fanhuiMapCenter } from '@/utils/map/areaCoordinate'
import mapDialog from '@/views/map/components/mapDialog.vue'
import regain from '@/components/common/map/regain.vue'
import mapTools from '@/components/common/map/mapTools.vue'
import mapLegend from '@/components/common/map/mapLegend.vue'
import mapIndex from '@/components/common/map/mapIndex.vue'
import mapLayer from '@/components/common/map/mapLayer.vue'

Vue.use(fullscreen)
/*地图*/
const centerlng = [119.41010268430291, 39.74080657918234], zoom = 10.23  //118.311974011,39.21539861
export default {
  components: {
    mapTools,
    mapLayer,
    mapIndex,
    mapLegend,
    mapDialog,
    regain
  },
  data() {
    return {
      map: null,
      center: false,
      mapBaseInfo:{
        target: "map",
        view: null,
        layers: null,
        controls: []
      },
      fullscreen: false,
      currentType: '卫星图',
      options: JSON.parse(sessionStorage.getItem('options')),
      mapHoverData: {},
      mapzujian:{
        vectorLayer: null,
        vectorLayerd: null,
        vectorSource: null,
        clickdian: null,
        draw: null,
        select: null,
        modify: null,
        editorBtnText: '编辑',
        overlay: null,
        textarr: '全屏',
        measureType: 'diatence',
        tipDiv: null,
        pointermoveEvent: null, // 地图pointermove事件
        sketchFeature: null, // 绘制的要素
        geometryListener: null, // 要素几何change事件
        measureResult: '0', // 测量结果
        pointLayer: null,
      }
    }
  },
  computed: {

  },
  created() {

  },
  mounted() {
    this.loadModules()
  },
  methods: {
    // 加载地图包
    loadModules() {
      loadScript(MapConfig.oljsurl1,'oldiyi').then(() => {
        loadScript(MapConfig.oljsurl2,'oldier').then(() => {
          loadScript(MapConfig.oljsurl3,'oldisan').then(() => {
            this.mapBaseInfo.view=new ol.View({
              center: centerlng, //中心点经纬度
              zoom: zoom, //图层缩放大小
              projection: "EPSG:4326",
              minZoom:1,
              maxZoom:18
            })
            this.mapBaseInfo.layers=[
              new ol.layer.Tile({
                opacity: 1,
                source: new ol.source.WMTS({
                  url: "http://t{0-7}.tianditu.gov.cn/img_c/wmts?tk=ffb3934ae2ecf35a45fb2b3b89d851b7",
                  layer: 'img',
                  matrixSet: 'c',
                  style: 'default',
                  version: '1.0.0',
                  format: 'tiles',
                  wrapX: true,
                  projection: "EPSG:4326",
                  tileGrid: new ol.tilegrid.WMTS({
                    tileSize: [256, 256],
                    // origin: [-186.01044257092096, 84.64696799925173],
                    // extent: [-186.01044257092096, -95.55476457260431, 185.65563085853216, 84.64696799925173],
                    // resolutions: this.getlods()[0],
                    // matrixIds: this.getlods()[1]
                    origin: [-180, 90],
                    extent: [-180, -90, 180, 90],
                    resolutions: this.getTdtLods()[0],
                    matrixIds: this.getTdtLods()[1]
                  })
                })
              })
              ,new ol.layer.Tile({
                opacity: 1,
                source: new ol.source.WMTS({
                  url: "http://10.122.2.138:8090/iserver/services/map-agscache-HSYSZJ/wmts100",
                  layer: 'HSYSZJ',
                  matrixSet: 'Custom_HSYSZJ',
                  style: 'default',
                  version: '1.0.0',
                  format: 'image/png',
                  wrapX: true,
                  projection: "EPSG:4326",
                  tileGrid: new ol.tilegrid.WMTS({
                    tileSize: [256, 256],
                    origin: [106.8173728583451, 50.8591431420287],
                    extent: [106.8173728583451, 28.33392657054668, 129.34258942982717, 50.8591431420287],
                    resolutions: this.getlods()[0],
                    matrixIds: this.getlods()[1]
                  })
                })
              })
            ]
            this.$nextTick(this.gisInit)
          })
        })
      })
    },
    // 全屏方法
    fullScreen() {
      this.$fullscreen.toggle(this.$el.querySelector('.map-container-warp'), {
        wrap: false,
        callback: this.fullscreenChange
      })
    },
    fullscreenChange(fullscreen) {
      this.fullscreen = fullscreen
    },
    // 切换行政区图层
    changeCurrentType(data) {
      initTDTLayer(this.map, data)
    },
    // 回到中心点
    changeCenter() {
      mapAndCenter(
        centerlng[0],
        centerlng[1],
        this.map,
        zoom
      )
    },
    // 自定义切换中心点
    changeCenters(val) {
      const {lon, lat, zoom} = fanhuiMapCenter(val.code)
      mapAndCenter(
        lon,
        lat,
        this.map,
        Number(zoom)
      )
    },
    // 切换并高亮中心点
    changeMpaCenter(val){
      if(val['zoom']&&val['zoom']!=''){
        heightAndCenter(
          val.lon,
          val.lat,
          this.map,
          val['zoom']
        )
      }else{
        heightAndCenter(
          val.lon,
          val.lat,
          this.map
        )
      }
    },
    // 缩放地图
    changeMapZoom(val) {
      let view = this.map.getView()
      let zoom = view.getZoom()
      if (val === 'in') {
        if(zoom<=17){
          view.setZoom(zoom + 1)
        }
      } else {
        if(zoom>1){
          view.setZoom(zoom - 1)
        }
      }
    },
    // 测量
    changeceliang(type){
      let that = this

      if (this.mapzujian.draw != null) return false // 防止在绘制过程再创建测量
      this.mapzujian.measureType = type
      if (this.mapzujian.vectorLayer != null) this.clearMeasure()

      if(this.mapzujian.measureType!='point'){
        this.mapzujian.tipDiv = document.createElement('div')
        this.mapzujian.tipDiv.innerHTML = '单击确定起点'
        this.mapzujian.tipDiv.className = 'tipDiv'
        this.mapzujian.tipDiv.style = 'width: auto;height: auto;padding: 3px 5px;border: 1px solid rgb(255,0,0);font-size: 12px;line-height: 14px;background-color: rgb(255, 255, 255);color: rgb(51, 51, 51);position: relative;top: 60%;left: 60%;'
      }

      let overlay = new ol.Overlay({
        element: this.mapzujian.tipDiv,
        autoPan: false,
        positioning: 'bottom-center',
        id: 'tipLay',
        stopEvent: false, //停止事件传播到地图
      })
      this.map.addOverlay(overlay)

      this.mapzujian.pointermoveEvent = this.map.on('pointermove', (evt) => {
        overlay.setPosition(evt.coordinate)
      })
      if (this.mapzujian.measureType == 'distence') {
        this.creatDraw('LineString')
      } else if (this.mapzujian.measureType == 'area') {
        this.creatDraw('Polygon')
      } else if (this.mapzujian.measureType == 'point') {
        this.mapzujian.clickdian=this.map.on('singleclick', function(e) {
          var imgurl=require('@/assets/images/mapIcons/i_pin.png')
          const content= `<div class="dianjia"><img src="${imgurl}"/>
            <p>经度：${e.coordinate[0].toFixed(4)} 纬度${e.coordinate[1].toFixed(4)}</p></div>`;
          that.clearMeasure('point')
          that.creatMark(
            null,content,'point'
          ).setPosition(e.coordinate)
        })
      }
    },
    creatDraw(type) {
      let maxPoints = null
      // 矢量图层源
      let vectorSource = new ol.source.Vector({
        wrapX: false,
      })
      // 矢量图层
      this.mapzujian.vectorLayer = new ol.layer.Vector({
        zIndex: 3,
        source: vectorSource,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(0,0,0,0.25)',
          }),
          stroke: new ol.style.Stroke({
            color: 'rgb(255,0,0)',
            width: 2,
          }),
          image: new ol.style.Circle({
            radius: 0,
            fill: new ol.style.Fill({
              color: 'rgb(255,0,0)',
            }),
          }),
        }),
        name: '测量图层',
      })
      this.map.addLayer(this.mapzujian.vectorLayer)
      this.mapzujian.draw = new ol.interaction.Draw({
        zIndex: 3,
        source: vectorSource,
        type: type,
        maxPoints: maxPoints,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(0,0,0,0.25)',
          }),
          stroke: new ol.style.Stroke({
            color: 'rgb(255,0,0)',
            // lineDash: [10, 10],
            width: 2,
          }),
          image: new ol.style.Circle({
            radius: 0,
            fill: new ol.style.Fill({
              color: 'rgb(255,0,0)',
            }),
          }),
        }),
        // 绘制时点击处理事件
        condition: (evt) => {
          // 测距时添加点标注
          if (
            this.mapzujian.measureResult != '0' &&
            !this.map.getOverlayById(this.mapzujian.measureResult) &&
            this.mapzujian.measureType == 'distence'
          )
            this.creatMark(
              null,
              this.mapzujian.measureResult,
              this.mapzujian.measureResult
            ).setPosition(evt.coordinate)
          return true
        },
      })
      this.map.addInteraction(this.mapzujian.draw)

      /**
       * 绘制开始事件
       */
      this.mapzujian.draw.on('drawstart', (e) => {
        this.mapzujian.sketchFeature = e.feature
        let proj = this.map.getView().getProjection()
        //******距离测量开始时*****//
        if (this.mapzujian.measureType == 'distence') {
          this.creatMark(null, '起点', 'start').setPosition(
            this.map.getCoordinateFromPixel(e.target.downPx_)
          )
          this.mapzujian.tipDiv.innerHTML = '总长：0 m</br>单击确定地点，双击结束'
          this.mapzujian.geometryListener = this.mapzujian.sketchFeature
            .getGeometry()
            .on('change', (evt) => {
              this.mapzujian.measureResult = this.distenceFormat(
                ol.sphere.getLength(evt.target, {
                  projection: 'EPSG:4326',
                  radius: 6378137,
                })
              )
              this.mapzujian.tipDiv.innerHTML =
                '总长：' + this.mapzujian.measureResult + '</br>单击确定地点，双击结束'
            })
        }
        //******面积测量开始时*****//
        else if (this.mapzujian.measureType == 'area') {
          this.mapzujian.tipDiv.innerHTML = '面积：0米</br>继续单击确定地点'
          this.mapzujian.geometryListener = this.mapzujian.sketchFeature
            .getGeometry()
            .on('change', (evt) => {
              if (evt.target.getCoordinates()[0].length < 4)
                this.mapzujian.tipDiv.innerHTML =
                  '面积：0米</br>继续单击确定地点'
              else {
                this.mapzujian.measureResult = this.formatArea(
                  ol.sphere.getArea(evt.target, { projection: proj, radius: 6378137 })
                )
                this.mapzujian.tipDiv.innerHTML =
                  '面积：' + this.mapzujian.measureResult + '</br>单击确定地点，双击结束'
              }
            })
        }
      })

      /**
       * 绘制开始事件
       */
      this.mapzujian.draw.on('drawend', (e) => {
        let closeBtn = document.createElement('span')
        closeBtn.innerHTML = '×'
        closeBtn.title = '清除测量'
        closeBtn.style = 'width: 14px;height: 14px;line-height: 13px;text-align: center;border-radius: 14px;display: inline-block;color: rgb(19, 38, 64);background-color: rgb(184, 27, 27);font-weight: bolder;font-size: 14px;position: absolute;top: -24px;right: -1px;cursor: pointer;'
        closeBtn.addEventListener('click', () => {
          this.clearMeasure()
        })
        //******距离测量结束时*****//
        if (this.mapzujian.measureType == 'distence') {
          this.creatMark(closeBtn, null, 'close1').setPosition(
            e.feature.getGeometry().getLastCoordinate()
          )
          this.creatMark(
            null,this.mapzujian.measureResult,'length'
          ).setPosition(e.feature.getGeometry().getLastCoordinate())
          this.map.removeOverlay(this.map.getOverlayById(this.mapzujian.measureResult))
        }
        //******面积测量结束时*****//
        else if (this.mapzujian.measureType == 'area') {
          this.creatMark(closeBtn, null, 'close2').setPosition(
            e.feature
              .getGeometry()
              .getInteriorPoint()
              .getCoordinates()
          )
          this.creatMark(
            null,this.mapzujian.measureResult,'area'
          ).setPosition(
            e.feature
              .getGeometry()
              .getInteriorPoint()
              .getCoordinates()
          )
        }
        // 停止测量
        this.stopMeasure()
      })
    },
    creatMark(markDom, txt, idstr) {
      if (markDom == null) {
        markDom = document.createElement('div')
        markDom.innerHTML = txt
        if(idstr!='area'&&idstr!='point'){
          markDom.innerHTML+='<i style="width: 12px;height: 12px;border-radius: 10px;border: 2px solid rgb(220,20,60);background: rgb(255,165,0);display: inline-block;position: absolute;bottom: -18px;left: -6px;"></i>'
        }
        if(idstr!='point'){
          markDom.style = 'color: rgb(255,0,0);font-size: 12px;position: relative;left: 55%;top: -11px;'
        }
      }
      let overlay = new ol.Overlay({
        element: markDom,
        autoPan: false,
        positioning: 'bottom-center',
        id: idstr,
        stopEvent: false,
      })
      this.map.addOverlay(overlay)
      return overlay
    },
    distenceFormat(length) {
      let output
      if (length > 100) {
        output = Math.round((length / 1000) * 100) / 100 + 'km' //换算成km单位
      } else {
        output = Math.round(length * 100) / 100 + 'm' //m为单位
      }
      return output //返回线的长度
    },
    formatArea(area) {
      let output
      if (area > 10000) {
        output =
          Math.round((area / 1000000) * 100) / 100 + '平方千米' //换算成km单位
      } else {
        output = Math.round(area * 100) / 100 + '平方米' //m为单位
      }
      return output //返回多边形的面积
    },
    // 停止测量
    stopMeasure() {
      this.mapzujian.tipDiv = null
      this.map.removeInteraction(this.mapzujian.draw)
      this.mapzujian.draw = null
      this.map.removeOverlay(this.map.getOverlayById('tipLay'))
    },
    //清除测量
    clearMeasure(lei) {
      if(this.mapzujian.vectorLayer!=null){
        this.mapzujian.vectorLayer.getSource().clear()
      }
      if(this.mapzujian.vectorLayerd!=null){
        this.mapzujian.vectorLayerd.getSource().clear()
      }
      const data=this.map.getOverlays().getArray()
      let list=[]
      data.forEach((v,i) => {
        if(v.id!='pop'&&v.id!='hldian'&&v.id!='gldian'){
          list.push(v)
        }
      })
      list.forEach((v,i) => {
        this.map.removeOverlay(v)
      })
      //移除监听事件
      ol.Observable.unByKey(this.mapzujian.pointermoveEvent)
      ol.Observable.unByKey(this.mapzujian.geometryListener)
      this.mapzujian.pointermoveEvent = null
      this.mapzujian.geometryListener = null
      this.mapzujian.measureResult = '0'
      if(lei==undefined){
        ol.Observable.unByKey(this.mapzujian.clickdian)
        this.mapzujian.clickdian = null
      }
    },
    // 清除
    changeclear(){
      if(this.mapzujian.vectorLayer!=null){
        this.mapzujian.vectorLayer.getSource().clear()
      }
      if(this.mapzujian.vectorLayerd!=null){
        this.mapzujian.vectorLayerd.getSource().clear()
      }
      const data=this.map.getOverlays().getArray()
      let list=[]
      data.forEach((v,i) => {
        if(v.id!='pop'&&v.id!='hldian'&&v.id!='gldian'){
          list.push(v)
        }
      })
      list.forEach((v,i) => {
        this.map.removeOverlay(v)
      })
      //移除监听事件
      ol.Observable.unByKey(this.mapzujian.pointermoveEvent)
      ol.Observable.unByKey(this.mapzujian.geometryListener)
      this.mapzujian.pointermoveEvent = null
      this.mapzujian.geometryListener = null
      this.mapzujian.measureResult = '0'
      ol.Observable.unByKey(this.mapzujian.clickdian)
      this.mapzujian.clickdian = null
    },
    getlods(){
      var lods=[
        {
          level: 0,
          resolution: 0.04399456361617579
        },
        {
          level: 1,
          resolution: 0.021997325490126382
        },
        {
          level: 2,
          resolution: 0.010998662745063191
        },
        {
          level: 3,
          resolution: 0.0054993313725315955
        },
        {
          level: 4,
          resolution: 0.004283029810494504
        },
        {
          level: 5,
          resolution: 0.0027496656862657978
        },
        {
          level: 6,
          resolution: 0.0013748328431328989
        },
        {
          level: 7,
          resolution: 6.874164215664494E-4
        },
        {
          level: 8,
          resolution: 3.437082107832247E-4
        },
        {
          level: 9,
          resolution: 1.7185410539161236E-4
        },
        {
          level: 10,
          resolution: 8.592705269580618E-5
        },
        {
          level: 11,
          resolution: 4.296352634790309E-5
        },
        {
          level: 12,
          resolution: 2.1481763173951545E-5
        },
        {
          level: 13,
          resolution: 1.0740881586975772E-5
        }
      ]
      var resolutions=[],matrixIds=[]
      for(var i=0;i<lods.length;i++){
        resolutions.push(lods[i].resolution)
        matrixIds.push(lods[i].level)
      }
      return [resolutions,matrixIds]
    },
    getTdtLods() {
      var projection = ol.proj.get('EPSG:4326');
      var projectionExtent = projection.getExtent();
      var size = ol.extent.getWidth(projectionExtent) / 256;
      var resolutions = new Array(18);
      var matrixIds = new Array(18);
      for(var z=1;z<19;++z){
        resolutions[z]=size/Math.pow(2,z);
        matrixIds[z]=z;
      }
      return [resolutions,matrixIds]
    }
  }
}
